package com.sumauto.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.sumauto.R;

/*
 * Copyright:
 * Author: 		Lincoln
 * Description:
 * History:		2019/01/31
 */
public class HoleView extends FrameLayout {
    View anchor;
    Paint p = new Paint();
    Bitmap mBackground;
    private int resourceId;

    public HoleView(Context context) {
        this(context, null);
    }

    public HoleView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public HoleView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.HoleView);
        resourceId = a.getResourceId(R.styleable.HoleView_holeView, 0);
        a.recycle();
        //        p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        p.setColor(0x80000000);
        setWillNotDraw(false);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (mBackground == null || mBackground.getWidth() != w || mBackground.getHeight() != h) {
            mBackground = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
            Canvas canvas = new Canvas(mBackground);
            canvas.drawRect(0, 0, getWidth(), getHeight(), p);
            ViewGroup viewGroup = (ViewGroup) getParent();
            View anchor = viewGroup.findViewById(resourceId);
            if (anchor != null) {
                int[] outLocation = new int[2];
                anchor.getLocationOnScreen(outLocation);
                int anchorX = outLocation[0];
                int anchory = outLocation[1];

                getLocationOnScreen(outLocation);
                int x = outLocation[0];
                int y = outLocation[1];

                int l = anchorX - x;
                int t = anchory - y;
                canvas.drawRect(l, t, l + anchor.getMeasuredWidth(), t + anchor.getMeasuredHeight(), p);
            }
        }
    }


    @Override
    protected void onDraw(Canvas canvas) {
        if (mBackground != null) {
            canvas.drawBitmap(mBackground, 0, 0, null);
        }
    }
}
